package com.jsjosem.aftersales.service;

import static com.jsjosem.aftersales.constant.Command.NOTIFICATION_UNREAD_COUNT_UPDATE;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.igexin.sdk.GTIntentService;
import com.igexin.sdk.PushManager;
import com.igexin.sdk.message.GTCmdMessage;
import com.igexin.sdk.message.GTNotificationMessage;
import com.igexin.sdk.message.GTTransmitMessage;
import com.jsjosem.aftersales.R;
import com.jsjosem.aftersales.api.RetrofitClient;
import com.jsjosem.aftersales.api.UserApi;
import com.jsjosem.aftersales.data.request.CidParam;
import com.jsjosem.aftersales.data.response.BaseResponse;
import com.jsjosem.aftersales.data.response.EventNotification;
import com.jsjosem.aftersales.data.response.NotifyData;
import com.jsjosem.aftersales.listener.ListenerManager;
import com.jsjosem.aftersales.receiver.NotificationClickReceiver;
import com.jsjosem.aftersales.request.AsyncRequest;

import cn.hutool.core.util.StrUtil;
import retrofit2.Call;
import retrofit2.Retrofit;

/**
 * 继承 GTIntentService 接收来自个推的消息，所有消息在主线程中回调，如果注册了该服务，则务必要在 AndroidManifest 中声明，否则无法接受消息
 */
public class IntentService extends GTIntentService {

    private final static Retrofit retrofit;

    static {
        retrofit = RetrofitClient.getInstance();
    }

    @Override
    public void onReceiveServicePid(Context context, int pid) {
    }

    /**
     * 此方法用于接收和处理透传消息。透传消息个推只传递数据，不做任何处理，客户端接收到透传消息后需要自己去做后续动作处理，如通知栏展示、弹框等。
     * 如果开发者在客户端将透传消息创建了通知栏展示，建议将展示和点击回执上报给个推。
     */
    @Override
    public void onReceiveMessageData(Context context, GTTransmitMessage msg) {
        byte[] payload = msg.getPayload();
        String data = new String(payload);
        EventNotification<NotifyData> eventNotification = new Gson().fromJson(data, new TypeToken<EventNotification<NotifyData>>() {
        }.getType());
        String taskid = msg.getTaskId();
        String messageid = msg.getMessageId();

        // 弹出通知
        String channelId = "System Notifications";
        Intent intent = new Intent(this, NotificationClickReceiver.class);
        intent.putExtra("data", new Gson().toJson(eventNotification.getData()));
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        Notification notification = new Notification.Builder(context, channelId)
                .setContentTitle(eventNotification.getTitle())
                .setContentText(eventNotification.getContent())
                .setWhen(System.currentTimeMillis())
                .setAutoCancel(true)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(pendingIntent)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))   //设置大图标
                .build();

        // 更新通知的未读数量
        ListenerManager.getInstance().sendBroadCast(NOTIFICATION_UNREAD_COUNT_UPDATE, null, null);
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
        NotificationChannel channel = new NotificationChannel(channelId, "系统通知", NotificationManager.IMPORTANCE_DEFAULT);
        channel.enableLights(true);
        channel.enableVibration(true);
        notificationManager.createNotificationChannel(channel);
        notificationManager.notify(eventNotification.getData().getNotify_id(), notification);
    }

    // 接收 cid
    @Override
    public void onReceiveClientId(Context context, String clientid) {
        if (StrUtil.isNotBlank(clientid)) {
            CidParam cidParam = new CidParam();
            cidParam.setDevice_id(clientid);
            UserApi userApi = retrofit.create(UserApi.class);
            Call<BaseResponse<Void>> call = userApi.cid(cidParam);
            AsyncRequest<BaseResponse<Void>> request = new AsyncRequest<>();
            request.sendRequest(call, (res) -> {
                Log.e(TAG, "send cid -> " + "clientid = " + clientid);
            }, failedMessage -> Toast.makeText(this, failedMessage.toString(), Toast.LENGTH_SHORT).show());
        }
        Log.e(TAG, "onReceiveClientId -> " + "clientid = " + clientid);
    }

    // cid 离线上线通知
    @Override
    public void onReceiveOnlineState(Context context, boolean online) {
        Log.d(TAG, "onReceiveOnlineState -> " + "online = " + online);

    }

    // 各种事件处理回执
    @Override
    public void onReceiveCommandResult(Context context, GTCmdMessage cmdMessage) {
    }

    // 通知到达，只有个推通道下发的通知会回调此方法
    @Override
    public void onNotificationMessageArrived(Context context, GTNotificationMessage msg) {
        Log.d(TAG, "onNotificationMessageArrived -> " + new Gson().toJson(msg));
    }

    // 通知点击，只有个推通道下发的通知会回调此方法
    @Override
    public void onNotificationMessageClicked(Context context, GTNotificationMessage msg) {
        Toast.makeText(context, "title:" + msg.getTitle() + "\ncontent:" + msg.getContent() + "\ntaskId:" + msg.getTaskId() + "\nmessageId:" + msg.getMessageId(), Toast.LENGTH_LONG).show();
    }

    /**
     * 上报个推透传消息的展示回执。如果透传消息本地创建通知栏消息“展示”了，则调用此方法上报。
     */
    public boolean pushGtShow(Context context, String taskid, String messageid) {
        int gtactionid = 60001;//gtactionid传入60001表示个推渠道消息展示了
        return PushManager.getInstance().sendFeedbackMessage(context, taskid, messageid, gtactionid);
    }

    /**
     * 上报个推透传消息的点击回执。如果透传消息本地创建通知栏消息被“点击”了，则调用此方法上报。
     */
    public boolean pushGtClick(Context context, String taskid, String messageid) {
        int gtactionid = 60002;//gtactionid传入60002表示个推渠道消息点击了
        return PushManager.getInstance().sendFeedbackMessage(context, taskid, messageid, gtactionid);
    }

}
